/**
 * @file Serial.h
 * @author Beirnaert Simon
 * @brief Declares the class "Serial", which represents the robot's serial 
 * 	  port.
 */

#ifndef SERIAL_H
#define	SERIAL_H

#include <string>
#include <termios.h>

using namespace std;

/** Default serial device */
#define SERIAL_DEVICE		"/dev/ttyUSB0"
/** Default baudrate */
#define	SERIAL_BAUDRATE		38400
/** Default number of databits */
#define	SERIAL_DATABITS		8
/** Default number of parity bits */
#define	SERIAL_PARITY		0
/** Default number of stopbits */
#define SERIAL_STOPBITS		1
/** Default setting for flow control */
#define	SERIAL_FLOW_CONTROL	0
/** Max number of characters to read at once */
#define SERIAL_BUF_LEN		1000

/**
 * @brief Sets up the serial connection and exposes it to the program.
 */
class Serial{
	public:
		/** 
		 * @brief Set up the serial connection with default values.
		 */
		Serial();
		
		/**
		 * @brief Set up serial connection with given parameters.
		 *
		 * This will initiate a serial connection to the defined device
		 * and use the given parameters as attributes for that
		 * connection. The result is a fully configured serial
		 * connection which can be written to or read from.
		 *
		 * @param	string dev
		 * 		The serial device to connect to.
		 * @param	int baudrate
		 * 		The baudrate.
		 * @param	int databits
		 * 		The number of databits.
		 * @param	int parity
		 * 		The use of parity.
		 * @param	int stopbits
		 * 		The number of stopbits.
		 * @param	int flowControl
		 * 		The use of flow control.
		 */
		Serial(string dev, int baudrate, int databits, int parity,
		     	int stopbits, int flowControl);

		/** 
		 * @brief This will close the connection gracefully before 
		 * comitting suicide.
		 */
		~Serial();

		/**
		 * @brief Write string to the port.
		 *
		 * @param	string command
		 * 		The command to be written to the port.
		 * @return	Number of written characters on success, 
		 * 		-1 on failure.
		 */
		int swrite(string command);
		

		/**
		 * @brief Read from the port.
		 * 
		 * @param	char* result
		 * 		A pointer to the buffer that receives the output.
		 * @return 	The number of bytes read, -1 on error.
		 */
		int sread(char *result);

	private:
		string 	dev;
		speed_t baudrate;
		int	databits,
			parity,
			stopbits,
			flowControl,
			fd;

		/**
		 * @brief Actually set up the connection.
		 *
		 * This method gets called by the constructors and actually
		 * sets up the connection based on the attributes set by
		 * the constructors.
		 *
		 * @return 0 on success, 1 on failure.
		 */
		int setUp();

	protected:
		//No protected members yet
};

#endif
